﻿/*
--------------------------------------
File: CropLicenseplate.cs
Project: Themaopdracht 7
Author: Maarten Kroon

Description:
A algorithm which crops the image around the license plate, only for monochrome images
--------------------------------------
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;

namespace THO7_Team8
{
    class CropLicenseplate : VisionAlgorithm
    {
        public CropLicenseplate(String name)
            : base(name)
        {
            hasConfiguration = false;
        }

        public override System.Drawing.Bitmap DoAlgorithm(System.Drawing.Bitmap sourceImage)
        {
            int[] sourceArray = MyImage.BmpToArray(sourceImage);
            int width = sourceImage.Width;

            //Finds the dimensions for the new bitmap
            int firstX = width, firstY = 0, lastX = 0, lastY = 0;

            for (int i = 0; i < sourceArray.Length; i++)
            {
                if (sourceArray[i] != -16777216)
                {
                    //The first Y is the first non black pixel
                    if (firstY == 0)
                    {
                        firstY = i / width;
                    }
                    //The first X is the most left non black pixel
                    if (firstX > (i % width))
                    {
                        firstX = i % width;
                    }
                    //The last X pixel is the most right non black pixel
                    if ((i % width) > (lastX % width))
                    {
                        lastX = i % width;
                    }
                    //The last Y pixel is the last right non pixel
                    lastY = i / width;
                }
            }

            //Creates the new bitmap with the dimensions and the new array
            Bitmap croppedBitmap = new Bitmap(lastX - firstX, lastY - firstY);
            int[] croppedArray = MyImage.BmpToArray(croppedBitmap);

            //Crops the image
            int counter = 0;
            for (int y = firstY; y < lastY; y++)
            {
                for (int x = firstX; x < lastX; x++)
                {
                    croppedArray[counter] = sourceArray[y * width + x];
                    counter++;
                }
            }

            croppedBitmap = MyImage.ArrayToBmp(croppedArray, croppedBitmap);
            return croppedBitmap;
        }
    }
}






